﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Transit.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class ActionController : ControllerBase
    {
        static string accessKeyId = "LTAI5qekhKNrox6E";
        static string accessKeySecret = "j59ACP0PtlpANRfY9bbRm7lzTmBuh4";
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<ActionController> _logger;
        private readonly DefaultAcsClient _smsClient;
        public ActionController(ILogger<ActionController> logger)
        {
            _logger = logger;

            var profile = DefaultProfile.GetProfile("ap-northeast-1", accessKeyId, accessKeySecret);
            _smsClient = new DefaultAcsClient(profile);

        }

        [HttpGet("{signName}/{phoneNumbers}/{templateCode}/{templateParam}")]
        public ActionResult Sms([FromRoute]SmsTemplateInfo smsInfo)
        {
            if (string.IsNullOrWhiteSpace(smsInfo.PhoneNumbers) || string.IsNullOrWhiteSpace(smsInfo.TemplateParam))
            {
                return BadRequest("手机号与发送内容不能为空!");
            }
            var request = new CommonRequest
            {
                Method = MethodType.POST,
                Domain = "dysmsapi.aliyuncs.com",
                Version = "2017-05-25",
                Action = "SendSms"
            };
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", smsInfo.PhoneNumbers);
            request.AddQueryParameters("SignName", smsInfo.SignName);
            request.AddQueryParameters("TemplateCode", smsInfo.TemplateCode);
            request.AddQueryParameters("TemplateParam", smsInfo.TemplateParam);
            try
            {
                CommonResponse response = _smsClient.GetCommonResponse(request);
                return Ok("发送成功");
            }
            catch (ServerException e)
            {
                return BadRequest(e.Message);
            }
            catch (ClientException e)
            {
                return BadRequest(e.Message);
            }
        }

        [HttpGet("{key}")]
        public List<Company> Org(string key)
            => ThirdPartyOrgData.Gets(key).Data.Data;
    }

    public class SmsTemplateInfo
    {
        public string PhoneNumbers { get; set; }
        public string SignName { get; set; }
        public string TemplateCode { get; set; }
        public string TemplateParam { get; set; }
    }
    public class QueryData
    {
        public string OrderNumber { get; set; }
        public List<Company> Data { get; set; }

    }

    /// <summary>
    /// 企业信息
    /// </summary>
    public class Company
    {
        /// <summary>
        /// 企业编码
        /// </summary>
        public string CompanyCode { get; set; }
        /// <summary>
        /// 企业名称
        /// </summary>
        public string CompanyName { get; set; }
        /// <summary>
        /// 法人
        /// </summary>
        public string LegalPerson { get; set; }
        /// <summary>
        /// 企业状态
        /// </summary>
        public string CompanyStatus { get; set; }
        /// <summary>
        /// 社会统一信用代码
        /// </summary>
        public string CreditNo { get; set; }
        /// <summary>
        /// 注册日期
        /// </summary>
        public string EstablishDate { get; set; }
    }
    public class ThirdPartyOrgData
    {
        private const String host = "https://businessfuzzy.shumaidata.com";
        private const String path = "/getbusinessfuzzy";
        private const String method = "GET";
        private const String appcode = "eacca96f0aa04166bb70a4c4d7dea74f";

        public class OrgDataResponse
        {
            public string Msg { get; set; }
            public bool Success { get; set; }

            public int Code { get; set; }
            public QueryData Data { get; set; }
            public List<OrgItem> Items { get; set; }
        }

        public class OrgItem
        {
            public string CompanyName { get; set; }
            public string LegalPerson { get; set; }
            public string CreditNo { get; set; }
            public string EstablishDate { get; set; }
        }
        public static OrgDataResponse Gets(string keywords)
        {
            String querys = "keyword=" + keywords;
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (bodys.Length > 0)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Console.WriteLine(httpResponse.StatusCode);
            Console.WriteLine(httpResponse.Method);
            Console.WriteLine(httpResponse.Headers);
            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            var jsonStr = reader.ReadToEnd();
            var resp = JsonConvert.DeserializeObject<OrgDataResponse>(jsonStr);

            /* if (resp.Code == 200)
             {
                 resp.Items = JsonConvert.DeserializeObject<List<OrgItem>>(jsonStr);
             }
             else
             {
                 resp.Items = new List<OrgItem> { new OrgItem { CompanyName = "无此企业信息" } };
             }*/
            //Console.WriteLine(reader.ReadToEnd());
            //Console.WriteLine("\n");
            return resp;
        }
        public static OrgDataResponse GetsByInitOrg(string keywords)
        {
            String querys = "keyword=" + keywords;
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (bodys.Length > 0)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Console.WriteLine(httpResponse.StatusCode);
            Console.WriteLine(httpResponse.Method);
            Console.WriteLine(httpResponse.Headers);
            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            var jsonStr = reader.ReadToEnd();
            var resp = JsonConvert.DeserializeObject<OrgDataResponse>(jsonStr);

            /* if (resp.Code == 200)
             {
                 resp.Items = JsonConvert.DeserializeObject<List<OrgItem>>(jsonStr);
             }
             else
             {
                 resp.Items = new List<OrgItem> { new OrgItem { CompanyName = "无此企业信息" } };
             }*/
            //Console.WriteLine(reader.ReadToEnd());
            //Console.WriteLine("\n");
            return resp;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }
}
